package com.longnuoqi.mydoctor.activity;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.longnuoqi.mydoctor.adapter.NewsListViewAdapter;
import com.longnuoqi.mydoctor.entity.News;
import com.longnuoqi.mydoctor.utils.ActivityCollection;
import com.longnuoqi.mydoctor.utils.FileUtil;
import com.yunhe.mydoctor.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by Lenovo on 2016/1/7.
 */
public class NewsMoreActivity extends AppCompatActivity {
    private Intent intent;
    private ImageView back;

    private int id;
    private String url;

    private static final int LOAD_START = 1;
    private static final int LOAD_LOAD = 2;
    private int startList = 0;
    private List<News> newsList = new ArrayList<>();

    private PullToRefreshListView listView;//对应布局文件中的刷新组件
    private NewsListViewAdapter adapter;
    private static boolean isExit = false;//判断是否退出
    private static boolean hasTask = false;//判断是否是任务
    private Timer timer = new Timer();//声明timer对象，计时器
    private TimerTask timerTask = new TimerTask() {//为timer安排一次执行或重复执行的任务
        @Override
        public void run() {
            isExit = false;
        }
    };

    /*双击退出程序*/
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (!isExit) {
                isExit = true;
                Toast.makeText(NewsMoreActivity.this, "再按一次退出程序", Toast.LENGTH_SHORT).show();
                if (!hasTask) {
                    timer.schedule(timerTask, 2000);//安排在指定延迟后执行指定的任务
                }
            } else {
                ActivityCollection.finishAll();
                //回收资源
                System.exit(0);
            }
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.news_more_layout);
        ActivityCollection.addActivity(this);
        intent = getIntent();
        id = intent.getIntExtra("id", 0);
        url = "http://www.tngou.net/api/info/news?id=" + id + "&rows=15";
        Log.e("===================ok",url);
        initView();
        refresh();
    }

    private void initView() {
        back = (ImageView) findViewById(R.id.news_more_back_btn);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setResult(RESULT_OK, intent);
                finish();
            }
        });
        listView = (PullToRefreshListView) findViewById(R.id.list);
    }

    private void refresh() {
        //对刷新组件进行监听
        listView.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
            @Override
            public void onPullDownToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
            }

            @Override
            public void onPullUpToRefresh(PullToRefreshBase<ListView> pullToRefreshBase) {
                new GetDataTask().execute(LOAD_LOAD);
            }
        });
        listView.getLoadingLayoutProxy(false, true).setPullLabel("上拉加载...");
        listView.getLoadingLayoutProxy(false, true).setRefreshingLabel("正在加载中...");
        listView.getLoadingLayoutProxy(true, false).setReleaseLabel("松开加载更多...");
        new GetDataTask().execute(LOAD_START);
    }

    private class GetDataTask extends AsyncTask<Integer, Void, List<News>> {//异步任务类，三个参数：Void(没有参数),此处一般都放置外部传入的参数；ProgressBar，此处一般放置进度条对象；数据源
        int flag = 0;

        @Override
        protected void onProgressUpdate(Void... values) {
            super.onProgressUpdate(values);
            Toast.makeText(NewsMoreActivity.this, "已是最新数据…", Toast.LENGTH_SHORT).show();
        }

        //子线程请求数据
        @Override
        protected List<News> doInBackground(Integer... params) {
            List<News> list = new ArrayList<>();
            try {
                flag = params[0];
                String s = FileUtil.httpGetRequest(url);
                list = FileUtil.json4NewsItem(s);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return list;
        }

        //主线程更新UI
        @Override
        protected void onPostExecute(List<News> list) {
            //向刷新组件ListView中，添加一条记录，并刷新该组件
            switch (flag) {
                case LOAD_START:
                    Log.e("===============", "LOAD_START");
                    ListView actualListView = listView.getRefreshableView();//从刷新组件中，获取到刷新后的ListView
                    registerForContextMenu(actualListView);//将该ListView，注册到当前上下文
                    newsList = setList(list, 0, 5);
                    startList += 5;
                    adapter = new NewsListViewAdapter(NewsMoreActivity.this, newsList);
                    actualListView.setAdapter(adapter);
                    actualListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                        @Override
                        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                            int newsId = (int) (view.findViewById(R.id.news_item_title)).getTag();
                            Intent intent = new Intent(NewsMoreActivity.this, NewsContentActivity.class);
                            intent.putExtra("id", newsId);
                            startActivityForResult(intent, 0);
                        }
                    });
                    break;
                case LOAD_LOAD:
                    Log.e("===============", "LOAD_LOAD");
                    if (startList < 15) {
                        newsList.addAll(setList(list, startList, startList + 5));
                        startList += 5;
                    } else {
                        Toast.makeText(NewsMoreActivity.this, "没有更多数据…", Toast.LENGTH_SHORT).show();
                    }
                    break;
            }
            adapter.notifyDataSetChanged();//通知适配器，数据更新已经完成
            listView.onRefreshComplete();
            super.onPostExecute(list);
        }
    }

    private List<News> setList(List<News> list, int start, int end) {
        List<News> newsList = new ArrayList<>();
        for (int i = start; i < end; i++) {
            newsList.add(list.get(i));
        }
        return newsList;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityCollection.removeActivity(this);
    }
}
